import React, { Component } from 'react'
import {
  NavBar,
  WingBlank,
  List,
  WhiteSpace,
  InputItem,
  Button,
  Toast
} from 'antd-mobile'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Redirect } from 'react-router-dom'

import { login } from '../../redux/actions'
import Logo from '../../components/logo/logo'
import '../register/register.scss'



class Login extends Component {

  static propTypes = {
    login: PropTypes.func.isRequired,
    user: PropTypes.object.isRequired
  }

  state = {
    username: '', // 用户名
    password: '', // 密码
  }

  // 输入信息
  handleChange = (key, value)=>{
    this.setState({[key]: value})
  }

  // 点击登录
  hangleLogin = ()=>{
    const {username, password} = this.state
    if (!username) {
      Toast.fail('请输入用户名！', 1)
    } else if (!password) {
      Toast.fail('请输入密码！', 1)
    } else {
      this.props.login(this.state)
    }
  }

  // 点击注册
  toRegister = ()=>{
    this.props.history.replace('/register')
  }
  render() {
    const { message,redirectTo } = this.props.user
    // 请求失败返回提示
    if (message) {
      Toast.fail(message, 1)
    }
    if (redirectTo) {
      return <Redirect to={redirectTo} />
    }
    return (
      <div>
        <NavBar>海绵招聘</NavBar>
        <div className="Logo-wrap">
          <Logo />
        </div>
        <WingBlank>
          <List>
            <WhiteSpace />
            <InputItem placeholder="请输入用户名" onChange={value => this.handleChange('username', value)}>用户名</InputItem>
            <WhiteSpace />
            <InputItem type="password" placeholder="请输入密码" onChange={value => this.handleChange('password', value)}>密&nbsp;&nbsp;&nbsp;码</InputItem>
            <WhiteSpace style={{marginTop: '30px'}} />
            <Button type="primary" onClick={this.hangleLogin}>登&nbsp;&nbsp;&nbsp;录</Button>
            <WhiteSpace />
            <Button type="primary" onClick={this.toRegister}>注&nbsp;&nbsp;&nbsp;册</Button>
            <WhiteSpace />
          </List>
        </WingBlank>
      </div>
    )
  }
}

export default connect(
  state => ({ user: state.user }),
  { login }
)(Login) 

